import { useSeckill } from "../../hook/seckill"

import { useResSeckill } from "../../hook/seckill_res"
import { Card, Button, Space, Breadcrumb, Table, DatePicker, Modal, message, Input, Cascader } from 'antd';
import { useEffect, Fragment, useState } from "react"
import { useAssType } from "../../hook/ass_type";
import { useHistory } from "react-router-dom"
// 使用图标
import { ExclamationCircleOutlined } from '@ant-design/icons';
// 使用日期格式
import moment from 'moment'
export const Seckill_list = () => {

  const [{ rows, curPage, eachPage, total, }, { selectFromchildType, getSeckills, offState, onState, choseCurpage, choseEachpage, selectSeckill, selectFromToType,deleteSeckill }] = useSeckill()
  const [, { addReSeckills }] = useResSeckill()
  // 定义进行查询的数据
  const [selectdata, setSelect] = useState();
  const [{
    ChildAll,
    TotalAll,
    assType
  }, { getassType, addAssTypeToReducer }] = useAssType()
  // 定义
  const { confirm } = Modal;
  const history = useHistory()
  // 上架商品交互框
  function tryonState(_id, name) {
    confirm({
      title: `请确认是否将 《 ${name} 》 商品上线`,
      icon: <ExclamationCircleOutlined />,
      content: '请谨慎选择！！！',
      async onOk() {
        const data = await onState(_id)
        data == 1 ? message.success('上线成功') : message.error('失败请重试');
      },
      onCancel() {
        console.log(_id);
      },
    });
  }
  // 下架商品交互框
  function tryoffState(_id, name) {
    confirm({
      title: `请确认是否将 《 ${name} 》 商品下架`,
      icon: <ExclamationCircleOutlined />,
      content: '请谨慎选择！！！',
      async onOk() {
        const data = await offState(_id);
        data == 1 ? message.success('下线成功') : message.error('失败请重试');
      },
      onCancel() {
        console.log(_id);
      },
    });
  }

  // 按父类型查询的数据格式

  const totalData = []
  TotalAll.map(item => {
    totalData.push({ label: item.totalType_name, value: item._id })
  })

  // 父类查询函数
  async function selectTotalType(value) {
    const data = await selectFromToType({ Father_id: value[0] })
    message.success(`查询到：${data.length}条数据`)

  }
  // 子类查询函数
  async function selectChildType(value) {
    const data = await selectFromchildType({ child_id: value[1] })
    message.success(`查询到：${data.length}条数据`)
  }

  // 修改按钮事件
  function addRes(data) {
    const { commodity_id } = data
    const result = Object.assign(data, { commodity_id: commodity_id._id })
    addReSeckills(result)
    history.push(`/info/seckill_res`)

  }

  // 添加到购物车
  function toAddcart(_id) {
    history.push(`/info/shoppingCart-add/${_id}`)
  }
  // 页码变化时的函数
  function changpage(Page, each) {

    if (Page != curPage) choseCurpage(Page)
    if (each != eachPage) choseEachpage(each)

  }
  const { Search } = Input;

  // 查询的日期添加到状态
  function onSearch(value, data) {
    setSelect({ ...selectdata, Start_time: data })

  }
  // 输入的商品名字添加到状态
  function onSearch1(value) {
    setSelect({ ...selectdata, name: value.target.value })
  }
  // 单机确认按钮执行的函数
  async function select() {
    const data = await selectSeckill(selectdata)
    message.success(`查询到   ${data.length} 条数据`)
  }
// 删除活动
async function delData(_id){
 const data= await deleteSeckill({_id})
 data.ok?message.success(`删除成功`):message.error(`删除失败`)
}
// 查看全部
function selectinit(){
  getSeckills()
}

  // 当页面结构加载完成开始请求数据
  useEffect(() => {
    getSeckills()
  }, [curPage, eachPage])
  //日期格式
  const dateFormat = 'YYYY-MM-DD HH:mm:ss';
  const dateFormatday = 'YYYY-MM-DD'
  // 列表显示的字段和数据属性名的对应关系
  const columns = [
    {
      title: '商品名',
      dataIndex: 'name',
      key: 'name',
    }, {
      title: '价格',
      dataIndex: 'Price',
      key: 'Price',
    },
    {
      title: '限购数量',
      dataIndex: 'restricted',
      key: 'restricted',
    },
    {
      title: '销售总数',
      dataIndex: 'Total',
      key: 'Total',
    },
    {
      title: '已售数量',
      dataIndex: 'Sold',
      key: 'Sold',
    },
    {
      title: '开始时间',

      key: 'Start_time',
      render: (text, record, index) => {
        const date = record.Start_time
        return (
          <DatePicker disabled showTime defaultValue={moment(date)} format={dateFormat} />
        )
      }
    },
    {
      title: '结束时间',

      key: 'End_time',
      render: (text, record, index) => {
        const date = record.End_time
        return (
          <DatePicker disabled showTime defaultValue={moment(date)} format={dateFormat} />
        )
      }
    },
    {
      title: '活动类型',
      dataIndex: 'Sale_type',
      key: 'Sale_type',
    },
    {
      title: '是否在售',

      key: 'State',
      render: (text, record, index) => {
        const text1 = record.State ? "是" : "否"
        return (
          <Fragment> {text1}</Fragment>
        )
      }
    },

    {
      title: '操作',
      key: 'zip',
      render: (text, record, index) => {
        // console.log(record);
        const { State, _id, restricted, name = "甜皮鸭" } = record
        return (
          <Fragment>
            {/* <Button  onClick={()=>reviseStudent(_id)}>修改</Button> */}
            <Button type="primary" style={{ backgroundColor: "#00BFFF", border: "0" }} onClick={() => addRes(record)}>修改</Button>
            {State ? <Button danger style={{ marginLeft: "5px", backgroundColor: "#8B8989", border: 0, color: "white" }} onClick={() => tryoffState(_id, name)}>下架</Button> : <Button danger style={{ marginLeft: "5px", backgroundColor: "#FF6A6A", color: "white", border: 0 }} onClick={() => tryonState(_id, name)}>上线</Button>}
            <Button danger style={{ marginLeft: "5px", backgroundColor: "#228B22", border: 0, color: "white" }} onClick={() => toAddcart(_id)}>添加到购物车</Button>
            <Button danger style={{ marginLeft: "5px", backgroundColor: "#8B8989", border: 0, color: "white",backgroundColor: "#FF3030" }} onClick={() => delData(_id)}>删除</Button>
          </Fragment >
        )
      }
    },
  ];

  return (
    <Space direction="vertical" style={{ width: "100%" }}>

      <Card >
        <Breadcrumb>
          <Breadcrumb.Item>主页</Breadcrumb.Item>
          <Breadcrumb.Item>
            <a href="/#/info/seckill_list">秒杀活动</a>
          </Breadcrumb.Item>
        </Breadcrumb>

      </Card>
      <Card >
        <Card  bordered style={{borderWidth:2,marginBottom:"20px",padding:"0"}}>
          <div style={{ color: "#6495ED", fontSize: "22px" }}>
          <div>查询:</div>  
          <Button onClick={() => selectinit()} style={{marginBottom:"10px",marginTop:"10px"}}>查看全部</Button>           
          </div>
          <div style={{ marginBottom: "20px", width: "500px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>开始日期：<DatePicker format={dateFormatday} onChange={onSearch} /></span>
            <span> <Input onChange={onSearch1} placeholder="商品名字" /> </span>
            <span><Button onClick={() => select()} >查询</Button> </span>
          </div>
          <span>按总类型：</span>  <Cascader options={totalData} onChange={(value) => selectTotalType(value)} placeholder="总类型" />
          <span style={{ marginLeft: "20px" }}>按子类型：</span>  <Cascader options={assType} onChange={(value) => selectChildType(value)} placeholder="子类型" />
          <div style={{ height: "10px" }} />
        </Card >
        <Table rowKey={record => record._id} dataSource={rows} columns={columns}
          pagination={{ current: curPage, total: total, showTotal:function(total){
            return `总数：${total}`
        }, pageSizeOptions: [5, 10, 15,], pageSize: eachPage, defaultPageSize: eachPage, position: ["bottomCenter"], onChange: changpage }}
        />
      </Card>
    </Space>
  )

}